import os.path
import sys

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

import click
from operator import itemgetter

from dp_analysis.analysis.base import DrawBase
from dp_analysis.db.connection import Mysql
from dp_analysis.utils.data_search import search_region, search_cuisine
from dp_analysis.utils.decorate import decorate


class DrawTop10(DrawBase):
    """
    绘制各地区各菜系 口味，环境，服务及综合指数TOP10
    """
    def __init__(self):
        super().__init__()

        self.save_path = "top10/"

    @decorate(obj_name="DrawTop10")
    def analyse(self, db, cuisine_dict):
        for region, cuisine_list in cuisine_dict.items():
            for cuisine in cuisine_list:
                self.statistic_info(db, region, cuisine)

    def statistic_info(self, db, region, cuisine):
        print(f"{region}地区{cuisine}菜系开始加载数据...")
        comp_list, shop_name_list, taste_list, env_list, serve_list = list(), list(), list(), list(), list()
        with Mysql("dp", db) as mysql:
            connection = mysql.engine.connect()
            index = 0
            for (shop_id, taste, env, serve) in connection.execute(
                    f"SELECT shop_name, taste, environment, serve FROM shop_info "
                    f"WHERE region={region!r} AND category={cuisine!r};").fetchall():
                taste, env, serve = float(taste or 0.0), float(env or 0.0), float(serve or 0.0)
                comp_list.append((index, (taste + env + serve) / 3.0))
                taste_list.append(taste)
                env_list.append(env)
                serve_list.append(serve)
                shop_name_list.append(shop_id)

                index += 1
        comp_list.sort(key=itemgetter(1), reverse=True)
        comp_list = comp_list[:10][::-1]
        taste_list = [taste_list[index] for (index, _) in comp_list]
        env_list = [env_list[index] for (index, _) in comp_list]
        serve_list = [serve_list[index] for (index, _) in comp_list]
        shop_name_list = [shop_name_list[index] for (index, _) in comp_list]
        comp_list = [float("%.2f" % comp[1]) for comp in comp_list]

        print(f"{region}地区{cuisine}菜系数据加载完成！")
        self.draw_top10_line(comp_list, shop_name_list, taste_list, env_list, serve_list, self.save_path, region, cuisine)


@click.command()
@click.option("--db", default=0, help="请选择使用的数据库")
@click.option("--region", default="all", help="选择地区；12大地区通过helpers.py获取")
@click.option("--cuisine", default="all", help="选择菜系；所有菜系通过helpers.py获取")
def main(db, region, cuisine):
    region_list = list(search_region(db))
    if region != "all" and region not in region_list:
        raise Exception(f"输入地区{region}不在可选范围内...")
    region_list = region_list if region == "all" else [region]
    if region != "all" and cuisine != "all" and cuisine not in search_cuisine(db, region):
        raise Exception(f"{region}地区不包含{cuisine}热门菜系...")

    cuisine_dict = dict()
    if cuisine == "all":
        for region in region_list:
            cuisine_dict.setdefault(region, list(search_cuisine(db, region)))
    else:
        for region in region_list:
            cuisine_dict.setdefault(region, [cuisine])

    draw_top10 = DrawTop10()
    draw_top10.analyse(db, cuisine_dict)


if __name__ == '__main__':
    main()
